package my.pipeline;

import my.epoll.Native;
import my.socket.Socket;

import java.nio.ByteBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.StandardCharsets;

/**
 * @author fengbo
 */
public class DefaultChannelPipeline {

    private final Socket socket;

    public DefaultChannelPipeline(Socket socket) {
        this.socket = socket;
    }

    public DefaultChannelPipeline fireChannelRead(Object obj) {
        if (obj instanceof ByteBuffer) {
            ByteBuffer buf = (ByteBuffer) obj;
            try {
                String request = StandardCharsets.UTF_8.newDecoder().decode(buf).toString();
                // 去掉换行
                request = request.substring(0, request.length() - 2);
                if ("111".equals(request)) {
                    Native.eventFdWrite(socket.getEventLoop().getVfd(), 1L);
                }
                System.out.println(request);
            } catch (CharacterCodingException e) {
                e.printStackTrace();
            } finally {
                socket.getEventLoop().allocator().release(buf, buf.capacity());
            }
        }
        return this;
    }

    public Socket socket() {
        return socket;
    }
}
